package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.service.MqOpsService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import io.micrometer.common.util.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Author：yyj
 * @Package：com.atguigu.tingshu.album.receiver
 * @Project：tingshu_parent240829
 * @name：AlbumInfoReceiver
 * @Date：2025/2/5 19:59
 * @Filename：AlbumInfoReceiver
 */
@Component
@Slf4j
public class AlbumInfoReceiver {
    @Autowired
    private MqOpsService mqOpsService;
    @Autowired
    private RedisTemplate redisTemplate;

    //消息消费
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true", exclusive = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE))
    @SneakyThrows   // 可以绕开编译期间的异常 等运行时发现异常才抛出
    public void listenAlbumAndTrackStatNumUpdate(String content, Message message, Channel channel) {
        //1.获取消息进行判断
        if(StringUtils.isEmpty(content)){
            return;
        }
        //2.消费消息
        //先进行消息转换
        TrackStatMqVo trackStatMqVo = JSONObject.parseObject(content, TrackStatMqVo.class);

        //获取唯一标识
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            mqOpsService.listenAlbumAndTrackStatNumUpdate(trackStatMqVo);
            //手动应答
            channel.basicAck(deliveryTag,false);
        } catch (GuiguException e) {
            // 重试 消息继续能够被消费者消费
            String retryMsgKey = "retry:msg:" + trackStatMqVo.getBusinessNo();
            Long count = redisTemplate.opsForValue().increment(retryMsgKey);
            if (count >= 3) {
                log.error("消息重试了{}次，异常原因：{}，请人工排查", count, e.getMessage());
                channel.basicNack(deliveryTag, false, false);  // 删除掉
            } else {
                log.error("消息重试了{}次", count);
                channel.basicNack(deliveryTag, false, true);//true重新回到队列
            }
        } catch (Exception e) {
            log.error("手动应答期间，网络出现了抖动，但是业务已经被成功执行过，消息直接丢掉");
            channel.basicNack(deliveryTag, false, false);
        }


    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_ALBUM_STAT_UPDATE, durable = "true", exclusive = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_ALBUM_STAT_UPDATE))
    @SneakyThrows   // 可以绕开编译期间的异常 等运行时发现异常才抛出
    public void listenAlbumAndBuyNumUpdate(String orderNo, Message message, Channel channel) {
        //1.获取消息进行判断
        if (StringUtils.isEmpty(orderNo)) {
            return;
        }
        //2.消费消息
        //先进行消息转换
        //获取唯一标识
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            mqOpsService.updateAlbumAndBuyNum(orderNo);
            //手动应答
            channel.basicAck(deliveryTag, false);
        } catch (GuiguException e) {
            // 重试 消息继续能够被消费者消费
            String retryMsgKey = "retry:msg:" + orderNo;
            Long count = redisTemplate.opsForValue().increment(retryMsgKey);
            if (count >= 3) {
                log.error("消息重试了{}次，异常原因：{}，请人工排查", count, e.getMessage());
                channel.basicNack(deliveryTag, false, false);  // 删除掉
            } else {
                log.error("消息重试了{}次", count);
                channel.basicNack(deliveryTag, false, true);//true重新回到队列
            }
        } catch (Exception e) {
            log.error("手动应答期间，网络出现了抖动，但是业务已经被成功执行过，消息直接丢掉");
            channel.basicNack(deliveryTag, false, false);
        }

    }

    }